
#include <cstdio>
#include <BOpenGL>
#include <BCharEvent>
#include <BKeyEvent>
#include <BFocusEvent>
#include <BMouseEvent>
#include <BCharEvent>
#include <BDragEvent>
#include <BTextEdit>
#include <BPainter>
#include <BCursor>
#include <BDrag>
#include <BSystem>
#include <BScreen>
#include "IGlobal.h"
#include "IWindow.h"
#include "member_BWidget.h"

using namespace BWE;

extern BList<IWindowHolder> app_windows;

IWindow::IWindow(BWidget* widget)
{
	boss = widget;
	shared = false;
	drag = 0;

	focusing = false;
	hoverWidget = 0;
	focusWidget = 0;
	
	mouse_pressed = false;
	mouse_click_time = 0;

	tipsShown = false;
	tipsTick = 0;

	refresh = false;

	if (create())
	{
		app_windows.append(this);
	}
}
IWindow::~IWindow()
{
	//destroy();
}

void IWindow::update()
{
	BEvent event(Event_Update);
	updateWidget(boss, event);
	if (hoverWidget && tipsTick > 0 && !tipsShown)
	{
		clock_t now = clock();
		if (now - tipsTick > 1000)
		{
			tipsShown = true;
			refresh = true;
		}
	}
}
void IWindow::fresh()
{
	BEvent event(Event_Fresh);
	freshWidget(boss, event);
}
void IWindow::frame()
{
	if (!refresh)
		return;

	makeCurrent(true);
	BOpenGL::Init();
	{
		glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
		glClear(GL_COLOR_BUFFER_BIT);

		glDisable(GL_LIGHTING);
		glEnable(GL_CULL_FACE);
		glDisable(GL_DEPTH_TEST);

		glEnable(GL_BLEND);
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

		glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
		glHint(GL_POINT_SMOOTH_HINT, GL_NICEST);
		glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST);

		glDisable(GL_POLYGON_OFFSET_POINT);
		glDisable(GL_POLYGON_OFFSET_LINE);
		glDisable(GL_POLYGON_OFFSET_FILL);

		paintWidget(boss);

		drawWindow();
		//drawCursor();
		//drawDrag();
		drawTip();

		swapBuffers();
	}
	BOpenGL::Release();
	makeCurrent(false);

	refresh = false;
}

void IWindow::updateWidget(BWidget* widget, const BEvent& event)
{
	if (widget && widget->able())
	{
		static BEvent showEvent(Event_Show);
		showEvent.setTime(event.time());
		if (widget->visible() && widget_member(widget)->paint.neverShown && widget->rect().valid())
		{
			widget_member(widget)->paint.neverShown = false;
			widget_member(widget)->procEvent(showEvent);
		}
		widget_member(widget)->procEvent(event);
		for (int i = 0; i < widget->childCount(); i++)
		{
			BWidget* child = widget->child(i);
			updateWidget(child, event);
		}
	}
}
void IWindow::freshWidget(BWidget* widget, const BEvent& event)
{
	if (widget == 0 || !widget_member(widget)->visible)
		return;
	if (widget_member(widget)->refresh)
	{
		widget_member(widget)->refresh = false;
		const bool& rf = widget_member(widget)->refresh;
		widget_member(widget)->procEvent(event);
		widget_member(widget)->dirty = true;
		refresh = true;
	}
	for (int i = 0; i < widget->childCount(); i++)
	{
		BWidget* child = widget->child(i);
		freshWidget(child, event);
	}
}
void IWindow::paintWidget(BWidget* widget)
{
	if (!widget_member(widget)->visible)
		return;

	if (widget_member(widget)->dirty)
	{
		widget_member(widget)->frame();
	}

	BWidgetHolderArray& children = widget_member(widget)->children;
	for (int i = children.size() - 1; i >= 0; i--)
	{
		BWidget* child = children[i];
		paintWidget(child);
	}
}

void IWindow::drawWindow()
{
	int width = widget_member(boss)->size.width();
	int height = widget_member(boss)->size.height();
	glViewport(0, 0, width, height);

	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(0, width, height, 0, -1, 1);

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	glDisable(GL_CULL_FACE);

	BRect clip = boss->absoluteRect();

	glEnable(GL_TEXTURE_2D);
	drawWidget(boss, clip, BPoint(0, 0), clip.height());

	for (int i = 0; i < popupWidgets.size(); i++)
	{
		BWidget* widget = popupWidgets[i];
		drawPopupWidget(widget, clip, widget->absolutePos(), clip.height());
	}

	glBindTexture(GL_TEXTURE_2D, 0);
	glDisable(GL_TEXTURE_2D);
}
void IWindow::drawWidget(BWidget* widget, const BRect& clip, const BPoint& offset, int frameHeight)
{
	if (!widget_member(widget)->visible || popupWidgets.contain(widget))
		return;
	BSize size = widget->size();
	BRect ab_rect(offset, size);
	BRect view = ab_rect & clip;
	if (view.invalid())
		return;

	glViewport(view.x(), frameHeight - view.bottom(), view.width(), view.height());

	BRect area(view.pos() - ab_rect.pos(), view.size());
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(area.left() + 1, area.right(), area.bottom() - 1, area.top(), -1, 1);

	if (widget_member(widget)->tbo)
	{
		glBindTexture(GL_TEXTURE_2D, widget_member(widget)->tbo);

		int width = widget_member(widget)->size.width();
		int height = widget_member(widget)->size.height();
		
		glBegin(GL_QUADS);
		glTexCoord2f(0.0f, 1.0f);		glVertex2i(0, 0);
		glTexCoord2f(0.0f, 0.0f);		glVertex2i(0, height);
		glTexCoord2f(1.0f, 0.0f);		glVertex2i(width, height);
		glTexCoord2f(1.0f, 1.0f);		glVertex2i(width, 0);
		glEnd();
	}
	BWidgetHolderArray& children = widget_member(widget)->children;
	for (int i = children.size() - 1; i >= 0; i--)
	{
		BWidget* child = children[i];
		drawWidget(child, view, offset + child->pos(), frameHeight);
	}
}
void IWindow::drawPopupWidget(BWidget* widget, const BRect& clip, const BPoint& offset, int frameHeight)
{
	if (!widget_member(widget)->visible)
		return;
	BSize size = widget->size();
	BRect ab_rect(offset, size);
	BRect view = ab_rect & clip;
	if (view.invalid())
		return;
	glViewport(view.x(), frameHeight - view.bottom(), view.width(), view.height());

	BRect area(view.pos() - ab_rect.pos(), view.size());
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(area.left() + 1, area.right(), area.bottom() - 1, area.top(), -1, 1);

	if (widget_member(widget)->tbo)
	{
		glBindTexture(GL_TEXTURE_2D, widget_member(widget)->tbo);

		int width = widget_member(widget)->size.width();
		int height = widget_member(widget)->size.height();

		glBegin(GL_QUADS);
		glTexCoord2f(0.0f, 1.0f);		glVertex2i(0, 0);
		glTexCoord2f(0.0f, 0.0f);		glVertex2i(0, height);
		glTexCoord2f(1.0f, 0.0f);		glVertex2i(width, height);
		glTexCoord2f(1.0f, 1.0f);		glVertex2i(width, 0);
		glEnd();
	}
	BWidgetHolderArray& children = widget_member(widget)->children;
	for (int i = 0; i < children.size(); i++)
	{
		BWidget* child = children[i];
		drawWidget(child, view, offset + child->pos(), frameHeight);
	}
}
void IWindow::drawCursor()
{
	if (!hoverWidget)
		return;
	BPoint globalPos = boss->globalPos();
	BPoint cursorPos = BCursor::globalPos();
	BPoint point = cursorPos - globalPos;

	BCursor* cursor = hoverWidget->cursor();
	if (cursor && cursor->type() == Cursor_Custom)
	{
		BPainter painter(boss);

		BPoint origin = cursor->point();
		BSize size = cursor->size();
		int x = point.x() - origin.x();
		int y = point.y() - origin.y();
		int w = size.width();
		int h = size.height();

		BImage* image = cursor->image();
		if (image)
		{
			painter.setColor(255, 255, 255);
			painter.drawPoint(point);
			painter.drawImage(x, y, w, h, image);
		}
	}
}
void IWindow::drawDrag()
{
	if (!drag)
		return;
	BPoint globalPos = boss->globalPos();
	BPoint cursorPos = BCursor::globalPos();
	BPoint point = cursorPos - globalPos;

	BPainter painter(boss);

	BPoint origin;
	BSize size(100, 100);
	int x = point.x() - origin.x();
	int y = point.y() - origin.y();
	int w = size.width();
	int h = size.height();

	BImage* image = drag->image();
	if (image)
	{
		painter.setColor(255, 255, 255);
		painter.drawPoint(point);
		painter.drawImage(x, y, w, h, image);
	}
}
void IWindow::drawTip()
{
	if (!hoverWidget || !tipsShown)
		return;

	const BFont* font = boss->font();
	if (!font)
		return;

	const BString& tooltip = hoverWidget->tips();
	if (tooltip.empty())
		return;

	BSize tipsSize = font->textSize(tooltip);
	BRect tipsRect(tipsPoint, tipsSize);
	BRect rect(boss->size());

	int xoffset = 0;
	int yoffset = 0;
	if (tipsRect.left() < rect.left())
		xoffset += rect.left() - tipsRect.left();
	if (tipsRect.top() < rect.top())
		yoffset += rect.top() - tipsRect.top();
	if (tipsRect.right() > rect.right())
		xoffset += rect.right() - tipsRect.right();
	if (tipsRect.bottom() > rect.bottom())
		yoffset += rect.bottom() - tipsRect.bottom();
	tipsRect.move(xoffset, yoffset);

	BPainter painter(boss);

	glBindFramebuffer(GL_FRAMEBUFFER, 0);

	painter.setColor(Color_Background);
	painter.fillRect(tipsRect);
	painter.setColor(Color_Border);
	painter.drawRect(tipsRect);
	painter.setColor(Color_Text);
	painter.drawText(tipsRect, tooltip);
	//painter.setPointSize(5);
	//painter.drawPoint(tipsPoint);
}

bool IWindow::isMaxinumed()
{
	const BScreen* screen = BSystem::GetScreen(0);
	BSize size = getWindowSize();
	return size.width() >= screen->size().width() * 0.9 && size.height() >= screen->size().height() * 0.9;
}

bool IWindow::focus(BWidget* widget)
{
	if(focusWidget != widget)
	{
		if(focusWidget)
		{
			widget_member(focusWidget)->focus = false;
			BFocusEvent focusEvent(Focus_Out);
			widget_member(focusWidget)->procEvent(focusEvent);
			widget_member(focusWidget)->refresh = true;
			focusWidget = 0;
		}
		if (widget && widget->able() && widget->focusable())
		{
			widget_member(widget)->focus = true;
			BFocusEvent focusEvent(Focus_In);
			widget_member(widget)->procEvent(focusEvent);
			widget_member(widget)->refresh = true;
			focusWidget = widget;

			if (popupWidgets.contain(focusWidget) && popupWidgets.last() != focusWidget)
			{
				popupWidgets.remove(focusWidget);
				popupWidgets.append(focusWidget);
			}
		}
		refresh = true;
		return true;
	}
	return false;
}
bool IWindow::popup(BWidget* widget, bool flag)
{
	if (flag)
	{
		if (!popupWidgets.contain(widget))
		{
			popupWidgets.append(widget);
		}
		widget->setFocus(true);
	}
	else
	{
		popupWidgets.remove(widget);
		return true;
	}
	return false;
}

BWidget* IWindow::widgetUnderPoint(const BPoint& point)
{
	if (popupWidgets.size())
	{
		for (int i = popupWidgets.size() - 1; i >= 0;  i--)
		{
			BWidget* popupWidget = popupWidgets[i];
			BWidget* widget = findPopupWidget(popupWidget, point, boss->size());
			if (widget)
				return widget;
			if (popupWidget->modal())
				return 0;
		}
	}
	return findWidget(boss, point, boss->size());
}
BWidget* IWindow::findWidget(BWidget* widget, const BPoint& point, const BRect& clip)
{
	BRect rect = widget->rect();
	if (boss == widget)
		rect.setPos(0);
	BRect clipRect = rect & clip;
	if (!clipRect.contain(point))
		return 0;
	currentRect = clipRect;
	BPoint localPoint = point - rect.pos();
	BWidgetHolderArray& children = widget_member(widget)->children;
	for (int i = 0; i < children.size(); i++)
	{
		BWidget* child = children[i];
		if (!child->visible())
			continue;
		if (child->floating())
		{
			BWidget* ret = findWidget(child, localPoint, widget->size());
			if (ret)
				return ret;
			continue;
		}
		const BRect& clientRect = widget->clientRect();
		const BRect& leftRect = widget->rect(Part_Left);
		const BRect& topRect = widget->rect(Part_Top);
		const BRect& rightRect = widget->rect(Part_Right);
		const BRect& bottomRect = widget->rect(Part_Bottom);
		BRect childRect = child->rect();
		if (clientRect.intersect(childRect))
		{
			BWidget* ret = findWidget(child, localPoint, clientRect);
			if (ret)
				return ret;
		}
		if (topRect.intersect(childRect))
		{
			BWidget* ret = findWidget(child, localPoint, topRect);
			if (ret)
				return ret;
		}
		if (leftRect.intersect(childRect))
		{
			BWidget* ret = findWidget(child, localPoint, leftRect);
			if (ret)
				return ret;
		}
		if (rightRect.intersect(childRect))
		{
			BWidget* ret = findWidget(child, localPoint, rightRect);
			if (ret)
				return ret;
		}
		if (bottomRect.intersect(childRect))
		{
			BWidget* ret = findWidget(child, localPoint, bottomRect);
			if (ret)
				return ret;
		}
	}
	return widget;
}
BWidget* IWindow::findPopupWidget(BWidget* widget, const BPoint& point, const BRect& clip)
{
	BRect viewRect = widget->absoluteRect() & clip;
	if (!viewRect.contain(point))
		return 0;

	for (int i = 0; i < widget->childCount(); i++)
	{
		BWidget* child = widget->child(i);
		if (child->visible())
		{
			BWidget* ret = findPopupWidget(child, point, viewRect);
			if (ret)
				return ret;
		}
	}

	return widget;
}

void IWindow::procMousePress(BMouseEvent& mouseEvent)
{
#ifdef _WINDOWS_SYSTEM_
	SetCapture(hwnd);
#endif

	mouse_pressed = true;
	mouse_pressed_time = mouseEvent.time();
	mouse_pressed_pos = mouseEvent.absolutePos();
	
	BWidget* widget = widgetUnderPoint(mouse_pressed_pos);
	this->focus(widget);
	if (focusWidget)
	{
		mouseEvent.setPos(mouseEvent.absolutePos() - focusWidget->absolutePos());
		widget_member(focusWidget)->procEvent(mouseEvent);
	}
}
void IWindow::procMouseRelease(BMouseEvent& mouseEvent)
{
	mouse_pressed = false;

	if (focusWidget)
	{
		mouseEvent.setPos(mouseEvent.absolutePos() - focusWidget->absolutePos());
		widget_member(focusWidget)->procEvent(mouseEvent);
	}
	if (focusWidget && hoverWidget && focusWidget == hoverWidget && mouse_click_time != 0)
	{
		int distance = (mouseEvent.absolutePos() - mouse_click_pos).length();
		double interval = mouseEvent.time() - mouse_click_time;
		if (distance < 5 && interval < 0.5)
		{
			mouseEvent.setType(Event_DoubleClick);
			mouseEvent.setPos(mouseEvent.absolutePos() - focusWidget->absolutePos());
			widget_member(focusWidget)->procEvent(mouseEvent);
			mouse_click_time = 0;
			return;
		}
	}
	if (focusWidget)
	{
		int distance = (mouseEvent.absolutePos() - mouse_pressed_pos).length();
		double interval = mouseEvent.time() - mouse_pressed_time;
		if (distance < 5 && interval < 1)
		{
			mouseEvent.setType(Event_MouseClick);
			mouseEvent.setPos(mouseEvent.absolutePos() - focusWidget->absolutePos());
			widget_member(focusWidget)->procEvent(mouseEvent);
			mouse_click_time = mouseEvent.time();
			mouse_click_pos = mouseEvent.absolutePos();
		}
	}
}
void IWindow::procMouseMove(BMouseEvent& mouseEvent)
{
	freshCursor();

	if (focusWidget && mouse_pressed)//block switch hovering widget
	{
		mouseEvent.setPos(mouseEvent.absolutePos() - focusWidget->absolutePos());
		widget_member(focusWidget)->procEvent(mouseEvent);
		return;
	}

	BPoint absolutePos = mouseEvent.absolutePos();
	BWidget* widget = widgetUnderPoint(absolutePos);
	if (hoverWidget != widget)
	{
		mouse_click_time = 0;
		if (hoverWidget)
		{
			BMouseEvent leaveEvent = mouseEvent;
			leaveEvent.setPos(mouseEvent.absolutePos() - hoverWidget->absolutePos());
			leaveEvent.setType(Event_MouseLeave);
			widget_member(hoverWidget)->procEvent(leaveEvent);
		}
		if (widget && widget->able())
		{
			BMouseEvent enterEvent = mouseEvent;
			enterEvent.setPos(mouseEvent.absolutePos() - widget->absolutePos());
			enterEvent.setType(Event_MouseEnter);
			widget_member(widget)->procEvent(enterEvent);
		}
		hoverWidget = widget;
		tipsPoint = absolutePos;
		tipsShown = false;
		if (widget && widget_member(widget)->tips.empty())
			tipsTick = 0;
		else
			tipsTick = clock();
	}
	if (hoverWidget && hoverWidget->able())
	{
		mouseEvent.setPos(mouseEvent.absolutePos() - hoverWidget->absolutePos());
		widget_member(hoverWidget)->procEvent(mouseEvent);
	}
}
void IWindow::procMouseWheel(BMouseEvent& mouseEvent)
{
	if (hoverWidget && hoverWidget->able())
	{
		widget_member(hoverWidget)->procEvent(mouseEvent);
	}
}
void IWindow::procDragMove(BDragEvent& dragEvent)
{
	drag = dragEvent.drag();

	BPoint absolutePos = dragEvent.absolutePos();
	if (!boss->absoluteRect().contain(absolutePos))
		drag = 0;

	BWidget* widget = widgetUnderPoint(absolutePos);
	if (hoverWidget != widget)
	{
		widget->fresh();
		mouse_click_time = 0;
		if (hoverWidget)
		{
			dragEvent.setCursor(0);
			dragEvent.setType(Event_DragLeave);
			dragEvent.setPos(dragEvent.absolutePos() - hoverWidget->absolutePos());
			widget_member(hoverWidget)->procEvent(dragEvent);
		}
		if (widget && widget->able())
		{
			dragEvent.setCursor(0);
			dragEvent.setType(Event_DragEnter);
			dragEvent.setPos(dragEvent.absolutePos() - widget->absolutePos());
			widget_member(widget)->procEvent(dragEvent);
		}
		hoverWidget = widget;
	}
	if (hoverWidget && hoverWidget->able())
	{
		dragEvent.setType(Event_DragMove);
		dragEvent.setPos(dragEvent.absolutePos() - hoverWidget->absolutePos());
		widget_member(hoverWidget)->procEvent(dragEvent);
	}
}
void IWindow::procDragDrop(BDragEvent& dragEvent)
{
	widget_member(hoverWidget)->procEvent(dragEvent);
	drag = 0;
}

